package login

import (
	"github.com/zachary/tbox/internal/svc"
	"github.com/zachary/tbox/internal/types"
	"github.com/zachary/tbox/internal/util"
	util2 "github.com/zachary/tbox/internal/web/util"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
)

var tempUser = types.UserLoginReq{
	Username: "admin",
	Password: "admin",
}

func TempUpLoginHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {

		var req types.UserLoginReq
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}
		if req.Username == tempUser.Username && req.Password == tempUser.Password {
			// 验证成功,生成测试数据
			token := types.TokenClaims{
				UserId:   1000,
				UserName: tempUser.Username,
				UserType: "WEB",
				Role:     []string{"admin"},
				Ext:      map[string]any{"ex1": "val1", "ext2": "val2"},
			}
			secret := svcCtx.Config.Auth.AccessSecret
			expire := svcCtx.Config.Auth.AccessExpire
			jwtToken, err := util.GetJwtToken(secret, expire, &token)
			if err != nil {
				httpx.ErrorCtx(r.Context(), w, err)
				return
			}
			token.Token = jwtToken
			httpx.OkJsonCtx(r.Context(), w, util2.Success(token))
		} else {
			httpx.WriteJsonCtx(r.Context(), w, http.StatusUnauthorized, util2.Fail("登录失败,用户名或密码错误!"))
		}
	}
}
